/*
** Main Game Routines by Neil C. Obremski                     [ Magenta's Maze ]
** 2017 Gibdon Moon Productions                   [ http://magsmaze.gibdon.com ]
**
** This is free and unencumbered software released into the public domain.
**
** Anyone is free to copy, modify, publish, use, compile, sell, or
** distribute this software, either in source code form or as a compiled
** binary, for any purpose, commercial or non-commercial, and by any
** means.
**
** In jurisdictions that recognize copyright laws, the author or authors
** of this software dedicate any and all copyright interest in the
** software to the public domain. We make this dedication for the benefit
** of the public at large and to the detriment of our heirs and
** successors. We intend this dedication to be an overt act of
** relinquishment in perpetuity of all present and future rights to this
** software under copyright law.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
** OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
** OTHER DEALINGS IN THE SOFTWARE.
**
** Tested w/ DOSBox 0.74, Microsoft C 5.10
 */
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <math.h>

#include "mag-cga.h"
#include "mag-bios.h"
#include "mag-inp.h"
#include "mag-math.h"
#include "mag-3d.h"		/* need CGA before including */
#include "mag-cube.h"
#include "mag-tree.h"
#include "mag-logo.h"
#include "mag-map.h"
#include "mag-puzz.h"
#include "mag-spkr.h"

char *version = "v1 " __DATE__;

char *commandlinehelp =
" [spellname] [/options]\n"
"\n"
"/ANI    Turn ON animation               /NOANI  Turn OFF animation\n"
"/BUF    Turn ON double-buffering        /NOBUF  Turn OFF double-buffering\n"
"/JOY    Turn ON joystick                /NOJOY  Turn OFF joystick\n"
"/SFX    Turn ON sound effects           /NOSFX  Turn OFF sound effects\n"
"/PWM    Turn ON digitized voice         /NOPWM  Turn OFF digitized voice\n"
"/LOW    Turn ON low-quality 3D          /NOLOW  Turn OFF low-quality 3D\n"
;

char *hints[] = {
	"the FOREST is full of MAGIC...",
	"Magenta is an Algebraic Spirit",
	"correct NUMBERS cast the SPELL",
	"Use arrow keys  to turn & move",
	"Press SPACE to hold/drop CUBES",
	"(held cube shown on the right)",
	"find ROOTS  to the  POLYNOMIAL",
	"(equation shown on the bottom)",
	"place  CUBES  in MAGIC CIRCLES",
	"(those connected by ley lines)",
	"... or WANDER the MAZE FOREVER",
};
#define HINT_MAX 11

int game(char, char, char, unsigned char far*);
void hud(int, int, int, char);
int main(int, char*[]);
char msgbox(int, int, char*, int);

/* returns TRUE if game is won, otherwise FALSE */
int game(char sfx, char pwm, char animate, unsigned char far *dbuf)
{
	char keeploop = TRUE;
	int i, x, y;
	int turning = 0, turndir = 0;
	int moving = 1, moveinc = 0;
	char redraw = TRUE;
	char dovoice = 0;
	char holding = 0; /* cube being held */
	char waitforinput = animate ? FALSE : TRUE;
	int movecount = 0;
	time_t curtime = time(0);
	int curfps, fps;
	int compass = pos.facing;

	/* draw interface */
	cls(BLACK);
	boxfill(256,0, 319,190, CYAN);
	color(BLACK, CYAN);
	titleblit(256,0, magic.spell, 8);
	for (y = 0; y < MAP_H; y++) {
		for (x = 0; x < MAP_W; x++) {
			char mc = map[y][x];
			pset(x+256, y+16, mc ? (tiles[mc].value ? WHITE:CYAN) : BLACK);
		}
	}
	logo(256,106, 1,2, MAGENTA);
	box(259,184, 316,189, BLACK);
	tinyblit(260,185, version);
	hline(0,319,190, CYAN);
	hline(0,319,191, WHITE);
	hud(-1,-1,-1,-1);

	/* prepare to render first frame */
	viewmap();
	viewmagic();

	while (keeploop) {

		unsigned long timer = ticker()+1L; /* top framerate = 1/18.2 seconds */

		if (!turning && !moving) {
			switch (action(waitforinput)) {
				case ACT_LEFT:
					if (turnleft(animate)) {
						redraw = TRUE;
						if (animate) {
							turning = 9; turndir = 10; /* rotate WORLD right */
						} else {
							turning = 1;
						}
					}
					break;

				case ACT_RIGHT:
					if (turnright(animate)) {
						redraw = TRUE;
						if (animate) {
							turning = 9; turndir = 350; /* rotate WORLD left */
						} else {
							turning = 1;
						}
					}
					break;

				case ACT_UP:
					if (move(animate)) {
						redraw = TRUE;
						if (animate) {
							moving = 9; moveinc = -11;
						} else {
							moving = 1;
						}
						movecount++;
					} else {
						if (sfx) {
							SFX_BUMP();
						}
					}
					break;

				case ACT_DOWN:
					break;

				case ACT_ESC:
					color(MAGENTA, BLACK);
					keeploop = msgbox(0,0,"QUIT [Y/N]?",-1) ? FALSE : TRUE;
					if (keeploop) {
						redraw = TRUE; /* draw-over message box */
					}
					break;

				case ACT_USE:
					if (holding && placecube(holding)) {		/* solve */
						redraw = TRUE;
						dovoice = holding;
						holding = 0;
						viewmagic();
						if (solved()) {
							keeploop = FALSE;
						} else if (sfx) {
							SFX_PUTDOWN();
						}

					} else if (holding && !map[pos.y][pos.x]) {	/* drop cube */
						if (sfx) {
							SFX_PUTDOWN();
						}
						for (i = 0; i < TILE_MAX; i++) {
							if (tiles[i].value == holding) {
								map[pos.y][pos.x] = (char)i;
								holding = 0;
								clearpipe(TRUE);
								viewmap();
								redraw = TRUE;
								break;
							}
						}
					} else if (holding) { /* cannot drop here */
						if (sfx) {
							SFX_BUMP();
						}
					} else if (map[pos.y][pos.x]) {
						struct tile *t = &tiles[map[pos.y][pos.x]];
						if (t->value >= 1 && t->value <= 9) {	/* hold cube */
							if (sfx) {
								SFX_PICKUP();
							}
							map[pos.y][pos.x] = 0;
							holding = t->value;
							clearpipe(TRUE);
							viewmap();
							redraw = TRUE;
						}
					}
					break;
			}
		}

		if (moving) {			/* animate movement forward */
			eat();

			moving--;
			if (!moving) {
				clearpipe(TRUE);
				viewmap();
				viewmagic();
			} else { /* translate pipeline */
				movemagic(0, 0, moveinc, 0);
				for (i = 0; i < rsize; i++) {
					translate(rpipe[i], 0, 0, moveinc);
				}
			}

			redraw = TRUE;
		}

		if (turning) {			/* animate turning left or right */
			eat();

			turning--;
			if (!turning) {
				compass = pos.facing;
				clearpipe(TRUE);
				viewmap();
				viewmagic();
			} else { /* rotate pipeline */
				movemagic(0, 0, 0, turndir);
				for (i = 0; i < rsize; i++) {
					rotateyatz(rpipe[i], turndir, 100);
				}
				compass -= turndir;
				if (compass < 0) {
					compass += 360;
				}
			}

			redraw = TRUE;

		}

		if (redraw) {
			if (dbuf) {						/* use double buffer? */
				cga_vbuf = dbuf;
			}
			X_MAX = 255; Y_MAX = 190;		/* clip to 3D window */
			cls256(192, BLACK);				/* clear 3D window */
			drawmagic();					/* circles & leylines */
			pipeline(TRUE, TRUE, TRUE);		/* 3D objects */
			avatar(90, 50 + (moving > 4 ? moving - 9 : -moving));
			X_MAX = 319; Y_MAX = 199;		/* clip to entire screen */
			if (dbuf) {						/* copy double buffer to CGA */
				blit(256,192, dbuf,
				cga_vbuf = PTR_CGA_MEMORY);	/* restore direct drawing to CGA */
			}
			redraw = FALSE;
		}
		hud(compass,fps,movecount,holding);	/* update HUD directly in CGA */

		if (dovoice && pwm) {
			playemb(dovoice);
			dovoice = 0;
		}

		/* crude FPS tracker (ideally 17 or 18 due to default 18.2 ticker) */
		{
			while (ticker() < timer) {
				eat();						/* process keyboard buffer */
			}
			if (curtime == time(0)) {
				curfps++;
			} else {
				if (curfps != fps) {
					fps = curfps;
				}
				curfps = 0;
				curtime = time(0);
			}
		}
	}

	return solved() ? movecount : 0;
}

/* Heads Up Display */
void hud(int facing, int fps, int movecount, char holding)
{
	static char oldx = 0, oldy = 0, oldhold = -1;
	static int oldmove = 0, oldfps = 0, oldfacing = 0;
	char status[9];

	if (movecount < HINT_MAX<<1) { /* show hints in first 10 moves */
		color(WHITE, BLACK);
		textblit(8,8,hints[movecount>>1],30);
	}

	/* update status */
	if (oldfacing != facing || oldfps != fps || oldmove != movecount) {
		color(BLACK, CYAN);
		switch (oldfacing = facing) {
			case 0: status[0] = (char)24; break;
			case 90: status[0] = (char)26; break;
			case 180: status[0] = (char)25; break;
			case 270: status[0] = (char)27; break;
			default: status[0] = ' '; break;
		};
		status[1] = '\0';
		if (fps < 0) {
			fps = 0;
		} else if (fps > 99) {
			fps = 99;
		}
		sprintf(status+1, "%04d %02d", oldmove = movecount, oldfps = fps);
		textblit(256,56, status, 8);
	}

	/* update map position */
	if (pos.x != oldx || pos.y != oldy) {
		if (oldx && oldy) {
			pset(oldx+256,oldy+16, map[oldy][oldx] ? WHITE : BLACK);
		}
		pset((oldx = pos.x) + 256, (oldy = pos.y) + 16, MAGENTA);
	}

	/* update cube held and equation */
	if (oldhold != holding) {
		box(260,68, 315,104, WHITE);
		boxfill(261,69, 314,103, BLACK);
		color(WHITE, BLACK);
		if (holding) {
			giantc(278, 72, (char)(48 + holding));
		} else {
			giantc(278, 72, ' ');
		}
		oldhold = holding;

		/* draw equation */
		color(BLACK, WHITE);
		textblit(0,192, magic.equation, 40);
	}
}

int main(int argc, char *argv[])
{
	static char dialog[] = "MAGIC>        ";
	char animate = -1, buffer = -1;
	int i, oldmode = 3;
	unsigned char far *dbuf = 0;
	char loopmain = TRUE;
	char *spell = 0;
	char WALL_TILE;
	int won;
	char autojoy = TRUE;
	char sfx = TRUE, pwm = TRUE;
	char low3d = FALSE;
	char *exename = exefn(argv[0], __FILE__);

	if (tandy1000() || pcjr()) {
		autojoy = FALSE;	/* incorrectly detects joystick presence */
		low3d = TRUE;		/* mostly wireframe */
		pwm = FALSE;		/* significantly increases load time */
		animate = FALSE;	/* way too costly */
		buffer = FALSE;		/* too slow */
	}

	printf("Magenta's Maze (%s) compiled with %s\n", version, MAG_C);
	#ifndef NDEBUG
	puts("2017 Gibdon Moon Productions (http://magsmaze.gibdon.com) [DEBUG]");
	#else
	puts("2017 Gibdon Moon Productions (http://magsmaze.gibdon.com)");
	#endif
	puts("");

	/* process command-line arguments */
	for (i = 1; i < argc; i++) {
		char *parg = argv[i];

		if ('-' == *parg || '/' == *parg) {
			parg++;
		} else if (!spell) {
			spell = parg;
			loopmain = FALSE;
			continue;
		}

		if ('?' == *parg || !stricmp("help", parg)) {
			printf(exename);
			puts(commandlinehelp);
			return 0;
		} else if (!stricmp("buf", parg)) {
			buffer = TRUE;
		} else if (!stricmp("nobuf", parg)) {
			buffer = FALSE;
		} else if (!stricmp("ani", parg)) {
			animate = TRUE;
		} else if (!stricmp("noani", parg)) {
			animate = FALSE;
		} else if (!stricmp("joy", parg)) {
			joystart(JOY_STICK1);
			autojoy = FALSE;
		} else if (!stricmp("nojoy", parg)) {
			autojoy = FALSE;
		} else if (!stricmp("sfx", parg)) {
			sfx = TRUE;
		} else if (!stricmp("nosfx", parg)) {
			sfx = FALSE;
		} else if (!stricmp("pwm", parg)) {
			pwm = TRUE;
		} else if (!stricmp("nopwm", parg)) {
			pwm = FALSE;
		} else if (!stricmp("low", parg)) {
			low3d = TRUE;
		} else if (!stricmp("nolow", parg)) {
			low3d = FALSE;
		}
	}

	/* initialize */
	if (buffer) {
		printf("Init Buffer ... ");
		dbuf = _fmalloc(0x4000);
		if (dbuf) {
			printf("OK (%d bytes)\n", 0x4000);
		} else {
			printf("FAILED! (%d bytes)\n", 0x4000);
			return -1;
		}
	}

	if (autojoy) {
		joyauto();
	}
	if (JOY_STICK) {
		int joyact, stage = 0;
		time_t curtime = time(0), newtime, endtime = curtime + 5;

		puts("SWIRL JOYSTICK (rotate clockwise to all four corners)");
		do {
			joyact = action(FALSE);
			if ((newtime = time(0)) != curtime) {
				curtime = newtime;
				printf("Calibrating .... %d,%d (%d +%d ~%d)\n",
					JOY_X1, JOY_Y1, JOY_LO, JOY_HI, JOY_START);
				if (curtime >= endtime) {
					if (0 == stage) {
						puts("REST JOYSTICK (let go, back to center)");
					} else if (1 == stage) {
						puts("PRESS JOYSTICK BUTTON");
					} else {
						puts("JOYSTICK DETECTION FAILED (use keyboard)");
						joystart(0);
						pause();
						break;
					}
					endtime = curtime + 5;
					stage++;
				}
			}
		} while (0 == ((ACT_USE | ACT_ESC) & joyact));

		if (JOY_STICK) {
			if (JOY_LEFT(JOY_X1) || JOY_RIGHT(JOY_X1) ||
				JOY_UP(JOY_Y1) || JOY_DOWN(JOY_Y1)) {
				puts("CALIBRATION FAILED");
				joystart(0);
			} else {
				printf("Joystick ....... %d,%d (%d +%d ~%d)\n",
					JOY_X1, JOY_Y1, JOY_LO, JOY_HI, JOY_START);
			}
		}
	}
	printf("Init 3D ....... ");
	OX = 128; OY = 95; init3d();
	puts("OK");
	printf("Init Map ...... ");
	initmap();
	puts("OK");

	printf("Init Tiles .... ");
	for (i = 1; i <= 9; i++) {
		tile_cube((char)i, low3d);
	}
	WALL_TILE = tile_tree(low3d);
	puts("OK");

	if (pwm) {
		printf("Init PWM ...... %s\n", exename);
		initemb(exename);
	}

	/* graphics mode and render first frame */
	oldmode = screen(4);

	do {

		/* measure title rendering to gauge computer speed */
		i = titles();
		if (pwm) {
			playemb(0); /* title sample */
		}
		if (-1 == animate) {
			animate = i <= 50 ? TRUE : FALSE;
		}
		if (-1 == buffer && dbuf && i > 80) {
			_ffree(dbuf);
			dbuf = 0;
		}

		/* dialog to enter spell name */
		if (loopmain || !spell) {
			color(CYAN, BLACK);
			textblit(0, 24<<3, "Type QUIT to EXIT", -1);
			color(WHITE, BLACK);
			if (!msgbox(80, 96, dialog, -1)) {
				loopmain = FALSE;
				spell = 0;
			} else {
				spell = dialog + 6;
				if (!stricmp(spell, "quit    ") ||
					!stricmp(spell, "exit    ") ||
					!stricmp(spell, "q       ")) {
					loopmain = FALSE;
					spell = 0;
				}
			}
		} else {
			pause();
		}

		if (spell) {
			puzzle(spell, WALL_TILE); /* generate game board */

			won = game(sfx, pwm, animate, dbuf);

			cga_vbuf = PTR_CGA_MEMORY;

			if (won) {
				char buf[40];
				color(MAGENTA, BLACK);
				sprintf(buf, "You won in %d moves!", won);
				msgbox(0,0,buf,pwm ? 10 : -1);
			}
		}

	} while (loopmain);

	/* exit graphics */
	screen(oldmode);

	/* free/check resources */
	if (dbuf) {
		_ffree(dbuf);
	}

	quit3d();

	if (pwm) {
		quitemb();
	}

	return 0;
}

char msgbox(int x, int y, char *msg, int emb)
{
	int i, len = strlen(msg);
	char buf[41];
	char key;
	char *wp = buf + 1, *endp = wp + len;

	if (x <= 0) {
		x = (160 - (len << 2));
	}
	if (y <= 0) {
		y = 80;
	}

	/* top edge of message box */
	memset(buf, 0, sizeof(buf));
	for (i = 1; i < len + 1; i++) {
		buf[i] = (char)196;
	}
	buf[0] = (char)218; /* upper-left corner */
	buf[i] = (char)191; /* upper-right corner */
	textblit(x, y, buf, len + 2);

	/* bottom edge of message box */
	for (i = 1; i < len + 1; i++) {
		buf[i] = (char)196;
	}
	buf[0] = (char)192; /* lower-left corner */
	buf[i] = (char)217; /* lower-right corner */
	textblit(x, y+24, buf, len + 2);

	/* message */
	memcpy(buf+1, msg, len);
	buf[0] = (char)179; /* left side */
	buf[i] = (char)179; /* right side */
	titleblit(x, y+8, buf, len + 2);

	if (emb >= 0) {
		playemb(emb); /* magic boom! */
	}

	while (wp < endp) {
		if (*wp++ == '>') {
			break;
		}
	}

	if (wp < endp) { /* enter text into blank part of message */
		i = wp - buf;
		while (wp < endp) {
			*wp++ = ' ';
		}
		wp = buf + i;
		*wp = '_';
		titleblit(x, y+8, buf, len + 2);

		do {
			key = (char)getch();
			if ((key >= 'A' && key <= 'Z') ||
				(key >= 'a' && key <= 'z') ||
				(key >= '0' && key <= '9')) {
				if (wp < endp) {
					*wp++ = key;
					if (wp < endp) {
						*wp = '_';
					}
					titleblit(x, y+8, buf, len + 2);
				}
			} else if (key == 0x8) { /* backspace */
				if (wp < endp) {
					*wp = ' ';
				}
				wp--;
				if (*wp == '>') {
					wp++;
				} else {
					*wp = '_';
					titleblit(x, y+8, buf, len + 2);
				}
			} else if (key == 0x1B) { /* escape */
				return FALSE;
			}

		} while (key != 0xD);

		if (wp < endp) {
			*wp = ' ';
		}

		memcpy(msg, buf + 1, len);
		return *(wp-1) == '>' ? FALSE : TRUE;
	}

	if (pause() & ACT_ESC) {
		return FALSE;
	}

	return TRUE;
}
